//
//  TransitionAnimatorNormal.swift
//  Swift-app开发基础架构
//
//  Created by pro on 2017/8/16.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

import UIKit

class KZNormalAnimator: KZAnimator {

    override init() {
        
        super.init()
        
        toDuration = 0.5
        backDuration = 0.5
        
        toAnimation = KZAnimatedTransitioning(duration: toDuration, animatedClouse: {
            (context: UIViewControllerContextTransitioning) -> () in
            
            let containerView = context.containerView
            let toView = context.view(forKey: .to)!
            let fromView = context.view(forKey: .from)!
            
            containerView.addSubview(toView)
            containerView.bringSubview(toFront: toView)
            
            let mask = UIView(frame: containerView.bounds)
            mask.backgroundColor = UIColor.black
            containerView.insertSubview(mask, aboveSubview: fromView)
            
            mask.alpha = 0
            toView.transform = CGAffineTransform(translationX: kScreenWidth, y: 0)
            
            UIView.animate(withDuration: self.toDuration, animations: {
                
                toView.transform = CGAffineTransform.identity
                fromView.frame = containerView.bounds.offsetBy(dx: -kScreenWidth / 4, dy: 0)
                mask.alpha = 0.4
                mask.frame = fromView.frame
                
            }, completion: { (finished) in
                
                mask.removeFromSuperview()
                context.completeTransition(!context.transitionWasCancelled)
            })
        })
        
        backAnimation = KZAnimatedTransitioning(duration: toDuration, animatedClouse: {
            (context: UIViewControllerContextTransitioning) -> () in
            
            let containerView = context.containerView
            let toView = context.view(forKey: .to)!
            let fromView = context.view(forKey: .from)!
            
            containerView.addSubview(toView)
            containerView.bringSubview(toFront: fromView)
            
            let mask = UIView(frame: containerView.bounds)
            mask.backgroundColor = UIColor.black
            containerView.insertSubview(mask, aboveSubview: toView)
            
            toView.frame = containerView.bounds.offsetBy(dx: -kScreenWidth / 4, dy: 0)
            mask.alpha = 0.4
            mask.frame = toView.frame

            UIView.animate(withDuration: self.toDuration, animations: {
                
                fromView.transform = CGAffineTransform(translationX: kScreenWidth, y: 0)
                toView.frame = containerView.bounds
                mask.alpha = 0
                mask.frame = toView.frame
                
            }, completion: { (finished) in
                
                mask.removeFromSuperview()
                context.completeTransition(!context.transitionWasCancelled)
            })
        })
    }
}
